<?php

namespace app\modules\admin\controllers;

use app\models\BaseModel;
use Yii;
use app\models\ChannelVisit;
use yii\data\ActiveDataProvider;
use yii\data\ArrayDataProvider;
use yii\debug\models\timeline\DataProvider;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;

/**
 * ChannelVisitController implements the CRUD actions for ChannelVisit model.
 */
class ChannelVisitController extends BaseController
{
    /**
     * @inheritdoc
     */
    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['POST'],
                ],
            ],
        ];
    }

    /**
     * Lists all ChannelVisit models.
     * @return mixed
     */
    public function actionIndex()
    {
        //按天展示，按月(month)展示，按年(year)展示，默认按天(day)
        $time_type = $_GET['time_type'] ?? 'day';
        $data_size = $_GET['data_size'] ?? 10;

        $date_list = [];
        if($time_type == 'year') {
            for($i = 0; $i < $data_size; $i++) {
                $date_list[] = date('Y', strtotime("-$i years"));
            }
        } elseif ($time_type == 'month') {
            for($i = 0; $i < $data_size; $i++) {
                $date_list[] = date('Y-m', strtotime("-$i months"));
            }
        } else {
            for($i = 0; $i < $data_size; $i++) {
                $date_list[] = date('Y-m-d', strtotime("-$i days"));
            }
        }

        $allModels = [];
        foreach ($date_list as $date) {
            $visit_count = ChannelVisit::find()
                ->where("created_date like '$date%'")
                ->andWhere("action = 1")
                ->count();
            $down_count = ChannelVisit::find()
                ->where("created_date like '$date%'")
                ->andWhere("action = 2")
                ->count();
            $jump_count = ChannelVisit::find()
                ->where("created_date like '$date%'")
                ->andWhere("action = 3")
                ->count();
            $allModels[] = [
                'date' => $date,
                'visit_count' => $visit_count,
                'down_count' => $down_count,
                'jump_count' => $jump_count,
                'conversion' => ($visit_count + $jump_count) ? $down_count*100/($visit_count + $jump_count) : 0,
            ];
        }

        $provider = new ArrayDataProvider([
            'allModels' => $allModels,
            'pagination' => [
                'pageSize' => 10,
            ],
            'sort' => [
                'attributes' => ['date', 'jump_count', 'visit_count', 'down_count', 'conversion'],
            ],
        ]);

        return $this->render('index', [
            'dataProvider' => $provider,
        ]);
    }

    public function actionDetail()
    {
        $date = Yii::$app->request->get('date');

        // SELECT utm,count(if(action=1,true,null)) as visit, count(if(action=2,true,null)) as down FROM `channel_visit` GROUP BY utm;
        $model = ChannelVisit::find()
            ->select([
                'utm',
                'count(if(action=1,true,null)) as visit',
                'count(if(action=2,true,null)) as down',
                'count(if(action=3,true,null)) as jump',
                ])
            ->where("created_date like '$date%'")
            ->with('channel')
            ->groupBy('utm')
            ->asArray();
        $provider = new ActiveDataProvider([
            'query' => $model,
            'sort' => [
                'attributes' => ['utm', 'jump', 'channel.note', 'visit', 'down', 'conversion'],
            ],
        ]);

        return $this->render('detail', [
            'dataProvider' => $provider,
        ]);
    }

    public function actionLog()
    {
        $dataProvider = new ActiveDataProvider([
            'query' => ChannelVisit::find(),
        ]);
        return $this->render('log', [
            'dataProvider' => $dataProvider,
        ]);
    }

    /**
     * Displays a single ChannelVisit model.
     * @param integer $id
     * @return mixed
     */
    public function actionView($id)
    {
        return $this->render('view', [
            'model' => $this->findModel($id),
        ]);
    }

    /**
     * Creates a new ChannelVisit model.
     * If creation is successful, the browser will be redirected to the 'view' page.
     * @return mixed
     */
    public function actionCreate()
    {
        $model = new ChannelVisit();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Updates an existing ChannelVisit model.
     * If update is successful, the browser will be redirected to the 'view' page.
     * @param integer $id
     * @return mixed
     */
    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
            return $this->redirect(['view', 'id' => $model->id]);
        } else {
            return $this->render('update', [
                'model' => $model,
            ]);
        }
    }

    /**
     * Deletes an existing ChannelVisit model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     * @param integer $id
     * @return mixed
     */
    public function actionDelete($id)
    {
        $this->findModel($id)->delete();

        return $this->redirect(['index']);
    }

    /**
     * Finds the ChannelVisit model based on its primary key value.
     * If the model is not found, a 404 HTTP exception will be thrown.
     * @param integer $id
     * @return ChannelVisit the loaded model
     * @throws NotFoundHttpException if the model cannot be found
     */
    protected function findModel($id)
    {
        if (($model = ChannelVisit::findOne($id)) !== null) {
            return $model;
        } else {
            throw new NotFoundHttpException('The requested page does not exist.');
        }
    }
}
